<?php
//   +----------------------------------------------------------------------
//   | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//   | Licensed ( http://www.hdphp.cn/licenses/ )
//   | Author: Jack <sophia2152@qq.com>
//   | 官方网址: http://www.hdphp.cn
//   | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//   | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//   +----------------------------------------------------------------------
namespace app\websocket\handler;

use app\common\services\message\service\StoreServiceRecordServices;
use app\common\services\user\UserAuthServices;
use app\websocket\BaseHandler;
use app\websocket\Manager;
use app\websocket\Response;
use hdphp\exceptions\AuthException;

/**
 * Class：UserHandler
 * 创建人：Jack
 * 创建时间：2024/1/13 8:52
 * @package app\websocket\handler
 */
class UserHandler extends BaseHandler
{

    /**
     * 用户登陆
     * @param array    $data
     * @param Response $response
     * @return bool|mixed|\think\response\Json|null
     */
    public function login(array $data, Response $response)
    {
        // 游客登陆
        if (isset($data['tourist']) && $data['tourist']) {
            return $response->success();
        }

        if (!isset($data['token']) || !$token = $data['token']) {
            return $response->fail('授权失败!');
        }

        try {
            /** @var UserAuthServices $services */
            $services = app()->make(UserAuthServices::class);
            $authInfo = $services->parseToken($token);
        } catch (AuthException $e) {
            return $response->fail($e->getMessage());
        }

        $user = $authInfo['user'];
        /** @var StoreServiceRecordServices $service */
        $service = app()->make(StoreServiceRecordServices::class);
        $service->updateRecord(['to_uid' => $user->uid], ['online' => 1, 'type' => $res['form_type'] ?? 1]);
        // 给所有在线客服人员发送当前用户上线消息
        $this->manager->pushing($this->manager->userFd(Manager::KEFU_TYPE_NUM), $response->message('user_online', [
            'uid' => $user->uid,
            'online' => 1
        ])->getData(), $this->fd);

        return $response->success('login', $user->toArray());
    }

}